package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.apis.schedule.IScheduleClient;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.TaskTypeEnum;
import com.heima.model.schedule.dtos.Task;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.utils.common.ProtostuffUtil;
import com.heima.wemedia.service.WmNewsTaskService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.util.Date;

@Slf4j
@Service
@RequiredArgsConstructor
public class WmNewsTaskServiceImpl implements WmNewsTaskService {


    //远程调用延迟任务
    private final IScheduleClient scheduleClient;

    //自动审核
    private final WmNewsAutoScanServiceImpl wmNewsAutoScanServiceImpl;

    /**
     * 添加任务到延迟对列中
     *
     * @param id          文章的id
     * @param publishTime 发布时间 可以作为任务的执行时间
     */
    @Async
    @Override
    public void addNewsToTask(Integer id, Date publishTime) {

        log.info("延迟任务添加到延迟服务中开始");

        Task task = new Task();

        task.setExecuteTime(publishTime.getTime());
        task.setTaskType(TaskTypeEnum.NEWS_SCAN_TIME.getTaskType());
        task.setPriority(TaskTypeEnum.NEWS_SCAN_TIME.getPriority());

        WmNews wmNews = new WmNews();
        wmNews.setId(id);
        //将Wmnews对象序列化为字节 然后加到task中
        task.setParameters(ProtostuffUtil.serialize(wmNews));

        scheduleClient.addTask(task);

        log.info("延迟任务添加到延迟服务中结束");


    }

    /**
     * 消费任务 审核文章
     */
    @Scheduled(fixedRate = 1000)//固定频率 每一秒拉取一次
    @Override
    public void scanNewsByTask() {

        /*log.info("消费任务，审核文章  开始");*/

        //获取任务
        ResponseResult responseResult = scheduleClient.poll(TaskTypeEnum.NEWS_SCAN_TIME.getTaskType(), TaskTypeEnum.NEWS_SCAN_TIME.getPriority());

        if (responseResult.getCode().equals(200) && responseResult.getData() != null) {
            //将任务从json转化为task对象
            Task task = JSON.parseObject(JSON.toJSONString(responseResult.getData()), Task.class);

            //反序列化获取文章对象
            WmNews wmNews = ProtostuffUtil.deserialize(task.getParameters(), WmNews.class);

            //审核文章
            wmNewsAutoScanServiceImpl.autoScanWmNews(wmNews.getId());
        }


        /*log.info("消费任务，审核文章  结束");*/
    }
}

























